<template>
  <n-form
    ref="formRef"
    :class="containerClass"
    :model="comment"
    :rules="rules"
    :show-label="false"
    :show-feedback="false"
  >
    <div class="mb-26 flex items-center justify-between gap-20">
      <n-form-item path="title" class="flex-1">
        <n-input v-model:value="comment.title" type="text" placeholder="输入标题" />
      </n-form-item>
      <n-form-item path="language" class="flex-1">
        <n-select
          v-model:value="comment.language"
          placeholder="选择编程语言"
          :options="langOptions"
          max-tag-count="responsive"
        />
      </n-form-item>
      <n-button type="primary" :disabled="processing" :loading="processing" @click="handleSubmit">
        提交题解
      </n-button>
    </div>

    <RichTextEditor v-model:value="comment.content" />
  </n-form>
</template>

<script setup>
import { ref } from 'vue'
import RichTextEditor from '@/components/common/RichTextEditor.vue'

const props = defineProps({
  defaultLang: {
    type: String,
    default: null,
  },
  containerClass: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['submitValidated'])

// 配置
const langOptions = [
  { label: 'C', value: 'C' },
  { label: 'C++', value: 'C++' },
  { label: 'Java', value: 'Java' },
  { label: 'Python', value: 'Python' },
]

const langKeys = langOptions.map((item) => item.value)

// 表单规则
const rules = {
  title: {
    required: true,
    trigger: 'blur',
  },
  language: {
    required: true,
    trigger: 'blur',
  },
}
// 表单变量
const formRef = ref(null)
const comment = ref({
  title: '',
  language: langKeys.includes(props.defaultLang) ? props.defaultLang : null,
  content: '',
})
const processing = ref(false)

const handleSubmit = () => {
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      //表单验证通过

      const reg = /[\x00-\x08]|[\x0b-\x0c]|[\x0e-\x1f]|[\x7f-\x84]|[\x86-\x9f]/g
      const content = comment.value.content?.replace(reg, '') || ''
      const textContent = content.replace(/<[^>]+>/g, '')
      if (!textContent) {
        $message.error('正文内容不能为空')
        return
      }
      processing.value = true
      emit(
        'submitValidated',
        {
          //data
          title: comment.value.title,
          language: comment.value.language,

          content,
          textContent,
        },
        () => {
          // successCallback
          processing.value = false
          comment.value.title = ''
          comment.value.content = ''
        },
        () => {
          // failCallback
          processing.value = false
        }
      )
    }
  })
}
</script>
